/***********************************************
*	名称:排序-任意类型
*	说明:可以排序任意类型的切片
*	作者:钱纯净
************************************************/
package sort

import (
	"encoding/json"
	"errors"
	"fmt"
	"sort"
)

type SortAnyModel struct {
	list []interface{}                       //列表
	fn   func(interface{}, interface{}) bool //排序条件
	err  error                               //错误信息
}

func New(fn func(a, b interface{}) bool) *SortAnyModel {
	return &SortAnyModel{fn: fn}
}

func SortAny(fn func(a, b interface{}) bool) *SortAnyModel {
	return &SortAnyModel{fn: fn}
}

//需要[]interface类型,或者任意类型的子元素
func (this *SortAnyModel) Add(list ...interface{}) *SortAnyModel {
	this.list = append(this.list, list...)
	return this
}

func (this *SortAnyModel) Set(list []interface{}) *SortAnyModel {
	this.list = list
	return this
}

func (this *SortAnyModel) Sort() ([]interface{}, error) {
	sort.Sort(this)
	return this.list, this.err
}

//返回interface{},用类型断言

func (this *SortAnyModel) Bind(pointer interface{}) error {
	data, err := this.Sort()
	if err != nil {
		return err
	}
	bs, err := json.Marshal(data)
	if err != nil {
		return err
	}
	return json.Unmarshal(bs, pointer)
}

//------------------------

//实现自带排序接口
func (this *SortAnyModel) Len() int {
	return len(this.list)
}

//实现自带排序接口
func (this *SortAnyModel) Less(i, j int) bool {
	defer this.recove()
	return this.fn(this.list[i], this.list[j])
}

//实现自带排序接口
func (this *SortAnyModel) Swap(i, j int) {
	this.list[i], this.list[j] = this.list[j], this.list[i]
}

//捕捉错误(主要类型强转错误)
func (this *SortAnyModel) recove() {
	if err := recover(); err != nil {
		this.err = errors.New(fmt.Sprintln(err))
	}
}

//处理错误,panic
func (this *SortAnyModel) panicErr() {
	if this.err != nil {
		panic(this.err)
	}
}
